package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTCustRegisterHis
 * @Description:华盛证券 客户服务顾问 历史数据更新注册数据接口 --内部接口
 * @author: chieh
 * @date 2022-04-29 14:52:00
 *
 */

public class aipHSTCustRegisterHis implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTCustRegisterHis.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
			JSONObject inObject = new JSONObject(inData);
            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";
			
			def createBeginTime = GetJV(inObject, "createBeginTime");
			def createEndTime = GetJV(inObject, "createEndTime");
			if(createBeginTime=='' || createEndTime=='') {	
				def selectime=eliteBean.chaxun_sql("SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 DAY), '%Y-%m-%d 00:00:00') AS starttime,DATE_FORMAT(NOW(),'%Y-%m-%d 23:59:59') AS endtime","dataSource");
				createBeginTime = selectime.get(0).get("starttime");
				createEndTime = selectime.get(0).get("endtime");
				log.debug("当前时间1：" +createBeginTime);
				log.debug("当前时间2：" +createEndTime);
			}
			def lastId = "0";
			def pageSize = "20";
			boolean nextPage=true;
			
			while (nextPage) {
	            String sign_time=Instant.now().getEpochSecond();
	            log.debug("解析信息-" +  "sign_time: " + sign_time);
	
	            HashMap<String, String> paramHashMap = new HashMap<String, String>() {
	                {
						put("lastId", lastId);//初始传0，后续接口中有返回
						put("pageSize", pageSize);//页码，默认20
						put("createBeginTime", createBeginTime);
						put("createEndTime", createEndTime);
						put("sign_time", sign_time);
	                }
	            };
	
	            log.debug("paramHashMap：" + paramHashMap);
	            //自然排序 升序参数
	            signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
	            log.debug("sign加密MD5前：" + signfront);
	            signafter = Util.getMD5Str(signfront);
	            log.debug("sign加密MD5后：" + signafter);
	
	            //拼接接口入参
	            paramHashMap.put("client_key", appid);
	            paramHashMap.put("sign", signafter);
	
	            String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
	            log.debug("injson:" + injson);
	
	            totalData = Querypromocode(eliteBean, injson,dataSourceID);
				//解析SSO返回信息
				JSONObject jsonObject = new JSONObject(totalData);
				lastId = GetJV(jsonObject, "lastId");//下一页请求带上的值
				//nextPage = GetJV(jsonObject, "nextPage");//是否有下一页
				nextPage = Boolean.valueOf(GetJV(jsonObject, "nextPage"));
				log.debug("lastId0:" + lastId+"nextPage0:" + nextPage);				
			}
            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";


        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    //按照时间区间和lastId查询流式的分页接口 URI:	/ae/query-register-history	
    public static String Querypromocode(EliteBean eliteBean , String injson, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
		String lastId="";
		boolean nextPage =false;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL+"/ae/query-register-history";
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");
            JSONObject dataObject;

            log.debug("code:" + code);
            if(code == "00000") {
                dataObject = new JSONObject(result);
                lastId= GetJV(dataObject, "lastId");
                //nextPage = GetJV(dataObject, "nextPage");
				nextPage = Boolean.valueOf(GetJV(dataObject, "nextPage"));
				log.debug('lastId1：'+lastId+'nextPage1：'+nextPage);
				
				if(nextPage==true) {
					String dataList = GetJV(dataObject, "dataList");
	                log.debug('lastId2：'+lastId+'nextPage2：'+nextPage);
					
					
	                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	                String dateStr = dateformat.format(System.currentTimeMillis());
	
	                JSONArray arrJsonArray = new JSONArray(dataList);
	                int arrInt = arrJsonArray.length();
	                for (int i = 0; i < arrInt; i++) {
	                    JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
	                    
						String customerid =GetJV(arrSmsJson,"customerid");//华盛号
						String customername =GetJV(arrSmsJson,"customername");//姓名
						String phone =GetJV(arrSmsJson,"phone");//手机号
						String register =GetJV(arrSmsJson,"register");//注册渠道
						String register_id =GetJV(arrSmsJson,"register_id");//注册渠道ID
						String registertime =GetJV(arrSmsJson,"registertime");//注册时间
						String stashtime =GetJV(arrSmsJson,"stashtime");//暂存时间
						String audittime =GetJV(arrSmsJson,"audittime");//审核时间
						String invitertype =GetJV(arrSmsJson,"invitertype");//邀请类型
	                    String inviterhstno=GetJV(arrSmsJson,"inviterhstno");//邀请人华盛号
						String invitername =GetJV(arrSmsJson,"invitername");//邀请人姓名
						String registerstatus =GetJV(arrSmsJson,"registerstatus");//2（注册） 3（暂存） 4（审核中）
						
						if(registertime!=""){
							registertime="'"+registertime+"'";
						}else{
							registertime=null;
						}
						if(stashtime!=""){
							stashtime="'"+stashtime+"'";
						}else{
							stashtime=null;
						}
						if(audittime!=""){
							audittime="'"+audittime+"'";
						}else{
							audittime=null;
						}
						
						String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
						String Customer_Guid = "CUST_" + Temp_Guid;
						String Objective_Guid = "OBJE_" + Temp_Guid;
						String EliteTask_Guid = "TASK_" + Temp_Guid;
				
						def dataresult = eliteBean.update("insert into custregisterhis (customerid, customername, phone, register, register_id, registertime, stashtime,audittime,invitertype,inviterhstno,invitername,registerstatus,createtime) VALUES ('"+customerid+"','"+customername+"','"+phone+"','"+register+"','"+register_id+"',"+registertime+","+stashtime+","+audittime+",'"+invitertype+"','"+inviterhstno+"','"+invitername+"','"+registerstatus+"',now())", "dataSource");
						
						// 查询名单是否已经存在
						List custCountList = eliteBean.chaxun_sql("Select Customer_Guid From Customer Where Customer_Id = '" + customerid + "'", "dataSource");
						def r_Staff_Id="";
						def r_Rolegroup_Id="";
						if (custCountList.size() <= 0) {
							log.debug("[进入未分配池]");
							
							 String[] custTaskDealSQL = new String[3];
							// 插入Customer表
							custTaskDealSQL[0] = "Insert Into Customer" +
									"  (Customer_Guid," +
									"   Customer_Id," +
									"   customername," +
									"   Mobile," +
									"   stringfield13," +
									"   sq_9," +
									"   stringfield7," +
									"   stringfield9," +
									"   stashtime," +
									"   audittime," +
									"   Sq_5," +
									"   Sq_6," +
									"   Sq_7," +
									"   registerstatus," +
									"   Createdby," +
									"   Createddate)" +
									"  Select '" + Customer_Guid + "'," +
									"         customerid," +
									"         customername," +
									"         phone," +
									"         register," +
									"         register_id," +
									"         registertime," +
									"         customerid," +
									"         stashtime," +
									"         audittime," +
									"         inviterhstno," +
									"         invitername," +
									"         invitertype," +
									"         registerstatus," +									
									"         'SELITE'," +
									"         now()" +
									"    From custregisterhis" +
									"   Where customerid = '"+customerid+"'"
	
							// 插入Objective表
							custTaskDealSQL[1] = "Insert Into Objective" +
									"  (Objective_Guid," +
									"   Objectivetype_Id," +
									"   Handleby_Id," +
									"   Handlegroup_Id," +
									"   Priority_Id," +
									"   Expireddate," +
									"   Customer_Guid," +
									"   Objectivestatus," +
									"   Iscontact," +
									"   Trytimes," +
									"   Successfulcontacttimes," +
									"   Createdby," +
									"   Createddate," +
									"   Obstatus," +
									"   Failure_Attempt," +
									"   Contact_Customer_Guid," +
									"   Passflag," +
									"   Lastassigndate," +
									"   Failstatus," +
									"   Successstatus," +
									"   Owner," +
									"   Workorderframe_Id," +
									"   Category," +
									"   Forecastdate," +
									"   Workorderid," +
									"   Workordertype1," +
									"   Workordertype2," +
									"   Workordertype3," +
									"   Workordertype4," +
									"   Objectivesubstatus," +
									"   Map_Id," +
									"   Curstep_Id_Map," +
									"   Max_Attempt," +
									"   Nocontacttry," +
									"   Allocation_Pool," +
									"   Appointment)" +
									"Values" +
									"  ('" + Objective_Guid + "'," +
									"   'RE0TX1'," +
									"   null," +
									"   null," +
									"   'NORMAL'," +
									"   Date_Add(Now(), Interval 1 Day)," +
									"   '" + Customer_Guid + "'," +
									"   'OPEN'," +
									"   0," +
									"   0," +
									"   0," +
									"   'SELITE'," +
									"   Now()," +
									"   'OPEN'," +
									"   999," +
									"   ''," +
									"   0," +
									"   Null," +
									"   '0'," +
									"   '0'," +
									"   ''," +
									"   'MY48ZX'," +
									"   'CASE'," +
									"   '2021-05-05 17:59:35'," +
									"   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
									"   'QL800E'," +
									"   'O7JIUV'," +
									"   ''," +
									"   ''," +
									"   'OPEN'," +
									"   'MY48ZX'," +
									"   'ONA0KD'," +
									"   0," +
									"   0," +
									"   0," +
									"   0)";
	
							// 插入EliteTask表
							custTaskDealSQL[2] = "Insert Into Elitetask" +
									"  (Elitetask_Guid," +
									"   Objective_Guid," +
									"   Objectivetype_Id," +
									"   Expectstarttime," +
									"   Expectendtime," +
									"   Obstatus," +
									"   Recordstatus," +
									"   Attempt," +
									"   Max_Attempt," +
									"   Handleby_Id," +
									"   Handlegroup_Id," +
									"   Createdby," +
									"   Createddate," +
									"   Failure_Attempt," +
									"   Comments," +
									"   Customer_Guid," +
									"   Localtrycount," +
									"   Lastassigndate," +
									"   Workorderframe_Id," +
									"   Curstepstatus," +
									"   Curstep_Id," +
									"   Stepforecastdate," +
									"   Curstep_Id_Map," +
									"   Map_Id," +
									"   Objectivesubstatus," +
									"   Elitetaskstatus," +
									"   Obflag,Maintaskstep_Id_Map)" +
									"Values" +
									"  ('" + EliteTask_Guid + "'," +
									"   '" + Objective_Guid + "'," +
									"   'RE0TX1'," +
									"   Now()," +
									"   Date_Add(Now(), Interval 3 Day)," +
									"   'OPEN'," +
									"   0," +
									"   1," +
									"   999," +
									"   null," +
									"   null," +
									"   'SELITE'," +
									"   Now()," +
									"   999," +
									"   ''," +
									"   '" + Customer_Guid + "'," +
									"   0," +
									"   Now()," +
									"   ''," +
									"   'OPEN'," +
									"   'ONA0KD'," +
									"   Now()," +
									"   'ONA0KD'," +
									"   'MY48ZX'," +
									"   'OPEN'," +
									"   'OPEN'," +
									"   1,'ONA0KD')";
									
									int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
									log.debug("老客户入库批量处理SQL返回结果："+batchSQLResult.toString());
									
								}
								List objCountList = eliteBean.chaxun_sql("select objective_guid from objective o left join Customer c on o.customer_guid=c.customer_guid where 1=1 and o.MAP_ID='MY48ZX' and  c.Customer_Id = '" + customerid + "'", "dataSource");
								if(custCountList.size() >= 0&&objCountList.size() <= 0) {
									def customer_guid = custCountList.get(0).get("customer_guid");
									log.debug("objective没有，但是存在customer_guid："+customer_guid);
									String[] custTaskDealSQL = new String[2];
									
									// 插入Objective表
									custTaskDealSQL[0] = "Insert Into Objective" +
											"  (Objective_Guid," +
											"   Objectivetype_Id," +
											"   Handleby_Id," +
											"   Handlegroup_Id," +
											"   Priority_Id," +
											"   Expireddate," +
											"   Customer_Guid," +
											"   Objectivestatus," +
											"   Iscontact," +
											"   Trytimes," +
											"   Successfulcontacttimes," +
											"   Createdby," +
											"   Createddate," +
											"   Obstatus," +
											"   Failure_Attempt," +
											"   Contact_Customer_Guid," +
											"   Passflag," +
											"   Lastassigndate," +
											"   Failstatus," +
											"   Successstatus," +
											"   Owner," +
											"   Workorderframe_Id," +
											"   Category," +
											"   Forecastdate," +
											"   Workorderid," +
											"   Workordertype1," +
											"   Workordertype2," +
											"   Workordertype3," +
											"   Workordertype4," +
											"   Objectivesubstatus," +
											"   Map_Id," +
											"   Curstep_Id_Map," +
											"   Max_Attempt," +
											"   Nocontacttry," +
											"   Allocation_Pool," +
											"   Appointment)" +
											"Values" +
											"  ('" + Objective_Guid + "'," +
											"   'RE0TX1'," +
											"   null," +
											"   null," +
											"   'NORMAL'," +
											"   Date_Add(Now(), Interval 1 Day)," +
											"   '" + Customer_Guid + "'," +
											"   'OPEN'," +
											"   0," +
											"   0," +
											"   0," +
											"   'SELITE'," +
											"   Now()," +
											"   'OPEN'," +
											"   999," +
											"   ''," +
											"   0," +
											"   Null," +
											"   '0'," +
											"   '0'," +
											"   ''," +
											"   'MY48ZX'," +
											"   'CASE'," +
											"   '2021-05-05 17:59:35'," +
											"   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
											"   'QL800E'," +
											"   'O7JIUV'," +
											"   ''," +
											"   ''," +
											"   'OPEN'," +
											"   'MY48ZX'," +
											"   'ONA0KD'," +
											"   0," +
											"   0," +
											"   0," +
											"   0)";
	
									// 插入EliteTask表
									custTaskDealSQL[1] = "Insert Into Elitetask" +
											"  (Elitetask_Guid," +
											"   Objective_Guid," +
											"   Objectivetype_Id," +
											"   Expectstarttime," +
											"   Expectendtime," +
											"   Obstatus," +
											"   Recordstatus," +
											"   Attempt," +
											"   Max_Attempt," +
											"   Handleby_Id," +
											"   Handlegroup_Id," +
											"   Createdby," +
											"   Createddate," +
											"   Failure_Attempt," +
											"   Comments," +
											"   Customer_Guid," +
											"   Localtrycount," +
											"   Lastassigndate," +
											"   Workorderframe_Id," +
											"   Curstepstatus," +
											"   Curstep_Id," +
											"   Stepforecastdate," +
											"   Curstep_Id_Map," +
											"   Map_Id," +
											"   Objectivesubstatus," +
											"   Elitetaskstatus," +
											"   Obflag,Maintaskstep_Id_Map)" +
											"Values" +
											"  ('" + EliteTask_Guid + "'," +
											"   '" + Objective_Guid + "'," +
											"   'RE0TX1'," +
											"   Now()," +
											"   Date_Add(Now(), Interval 3 Day)," +
											"   'OPEN'," +
											"   0," +
											"   1," +
											"   999," +
											"   null," +
											"   null," +
											"   'SELITE'," +
											"   Now()," +
											"   999," +
											"   ''," +
											"   '" + Customer_Guid + "'," +
											"   0," +
											"   Now()," +
											"   ''," +
											"   'OPEN'," +
											"   'ONA0KD'," +
											"   Now()," +
											"   'ONA0KD'," +
											"   'MY48ZX'," +
											"   'OPEN'," +
											"   'OPEN'," +
											"   1,'ONA0KD')";
											
											int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
											log.debug("老客户入库批量处理SQL返回结果："+batchSQLResult.toString());
										}
	
							
	                }
	                reJson = "{\"result\":\"1\",\"lastId\":"+lastId+",\"nextPage\":"+nextPage+"}";
				}else {
					reJson = "{\"result\":\"1\",\"lastId\":"+lastId+",\"nextPage\":"+nextPage+",\"message\":\"下拉完成\"}";
				}
            }else {
                String msg = GetJV(jsonObject, "msg");
                reJson = "{\"result\":\"-1\",\"message\":\"用户获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
        }
        return reJson;
    }

    // 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;

		try {
			Rev_Value = String.valueOf(inJson.getBoolean(getKey));
		} catch (Exception e6) {
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e5) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e4) {
					try {
						Rev_Value = String.valueOf(inJson.getLong(getKey));
					} catch (Exception e11) {
						try {
							Rev_Value = String.valueOf(inJson.getDouble(getKey));
						} catch (Exception e1) {
							try {
								Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
							} catch (Exception e2) {
								try {
									Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
								} catch (Exception e3) {
									Rev_Value = "";
								}
							}
						}
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			}
		}
		return Rev_Value;
	}


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
